package com.navi.mould1.service.impl;

import com.navi.bean.in.ConditionBean;
import com.navi.bean.out.halm_hourEfficiencyTrend_report.HalmHourEfficiencyTrendReportGridOut;
import com.navi.bean.sql.SqlVo;
import com.navi.mould1.pojo.ToolToolgLineFabPojo;
import com.navi.mould1.pojo.WaferSpecPojo;
import com.navi.mould1.reportUtils.LKingSortUtil;
import com.navi.mould1.service.IHalmHourEfficiencyTrendReportService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Service;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
import static com.navi.bean.sql.SqlVo.jointInSql;
import static com.navi.core.util.JdbcUtils.mySql_QueryRunner_QueryListBySql;
import static com.navi.mould1.reportUtils.ComputeUtil.getAverageRate;
import static com.navi.mould1.reportUtils.ComputeUtil.getRate;


@Slf4j
@Service
public class HalmHourEfficiencyTrendReportServiceImpl implements IHalmHourEfficiencyTrendReportService {


    public List<HalmHourEfficiencyTrendReportGridOut> getGridData(ConditionBean conditions) {

        //优化查询速度，把Sql中子查询拿出来单独查
        List<String> tool_id_fk_list = new ArrayList<>();
        if (StringUtils.isNotEmpty(conditions.getToolg_id()) || StringUtils.isNotEmpty(conditions.getTool_type()) || StringUtils.isNotEmpty(conditions.getTool_id())) {
            SqlVo sql = new SqlVo("select tool_id as tool_id_fk from bis_tool where 1=1");
            if (StringUtils.isNotEmpty(conditions.getToolg_id())) sql.appendSql("and root_tool_id in (select tool_id_fk from bis_tool_gr where toolg_id in " + jointInSql(conditions.getToolg_id()) + ")");
            if (StringUtils.isNotEmpty(conditions.getTool_type())) sql.appendSql("and unit_typ in" + jointInSql(conditions.getTool_type()));
            if (StringUtils.isNotEmpty(conditions.getTool_id())) sql.appendSql("and tool_id in" + jointInSql(conditions.getTool_id()));
            List<ToolToolgLineFabPojo> list = mySql_QueryRunner_QueryListBySql(sql, ToolToolgLineFabPojo.class);
            tool_id_fk_list.addAll(list.stream().map(data -> data.getTool_id_fk()).distinct().collect(Collectors.toList()));
        }
        List<String> wafer_spec_list = new ArrayList<>();
        if (StringUtils.isNotEmpty(conditions.getSpec()) || StringUtils.isNotEmpty(conditions.getWafer_spec())) {
            SqlVo sql = new SqlVo("select data_id as wafer_spec from bis_data where data_cate = 'WFSF'");
            if (StringUtils.isNotEmpty(conditions.getSpec())) sql.appendSql("and data_ext in" + jointInSql(conditions.getSpec()));
            if (StringUtils.isNotEmpty(conditions.getWafer_spec())) sql.appendSql("and data_id in" + jointInSql(conditions.getWafer_spec()));
            List<WaferSpecPojo> list = mySql_QueryRunner_QueryListBySql(sql, WaferSpecPojo.class);
            wafer_spec_list.addAll(list.stream().map(data -> data.getWafer_spec()).distinct().collect(Collectors.toList()));
        }

        final SqlVo sqlVo = new SqlVo();
        sqlVo.appendSql("SELECT");
        sqlVo.appendSql("CONCAT(input_date, ' ', input_time) as date,");
        sqlVo.appendSql("bin,");
        sqlVo.appendSql("eta_sum,");
        sqlVo.appendSql("total_count as count");
        sqlVo.appendSql("FROM icim_jn.halm_test_data_bin_summary A");
        sqlVo.appendSql("WHERE 1=1");
        //if (StringUtils.isNotEmpty(conditions.getFab_id())) sqlVo.appendSql("AND A.TOOL_ID_FK IN(select tool_id from icim_jn.bis_tool where fab_id_fk in" + jointInSql(conditions.getFab_id()) + ")");
        if (StringUtils.isNotEmpty(conditions.getBay_id())) sqlVo.appendSql("AND A.LINE_ID_FK in" + jointInSql(conditions.getBay_id()));
        //if (StringUtils.isNotEmpty(conditions.getToolg_id())) sqlVo.appendSql("AND A.TOOL_ID_FK in(select tool_id from bis_tool where root_tool_id in (select tool_id_fk from bis_tool_gr where toolg_id in " + jointInSql(conditions.getToolg_id()) + "))");
        //if (StringUtils.isNotEmpty(conditions.getTool_type())) sqlVo.appendSql("AND A.TOOL_ID_FK in(select tool_id from bis_tool where unit_typ in" + jointInSql(conditions.getTool_type()) + ")");
        //if (StringUtils.isNotEmpty(conditions.getTool_id())) sqlVo.appendSql("AND A.TOOL_ID_FK in" + jointInSql(conditions.getTool_id()));
        if (CollectionUtils.isNotEmpty(tool_id_fk_list)) sqlVo.appendSql("AND A.TOOL_ID_FK in" + tool_id_fk_list.stream().distinct().collect(Collectors.joining("','","('","')")));
        //if (StringUtils.isNotEmpty(conditions.getSpec())) sqlVo.appendSql("AND A.WAFER_SPEC in(select data_id from bis_data where data_cate = 'WFSF' and data_ext in" + jointInSql(conditions.getSpec()) + ")");
        //if (StringUtils.isNotEmpty(conditions.getWafer_spec())) sqlVo.appendSql("AND A.WAFER_SPEC in" + jointInSql(conditions.getWafer_spec()));
        if (CollectionUtils.isNotEmpty(wafer_spec_list)) sqlVo.appendSql("AND A.WAFER_SPEC in" + wafer_spec_list.stream().distinct().collect(Collectors.joining("','","('","')")));
        if (StringUtils.isNotEmpty(conditions.getManufacturer())) sqlVo.appendSql("AND A.CUS_ID_FK in" + jointInSql(conditions.getManufacturer()));
        if (StringUtils.isNotEmpty(conditions.getBase_id())) sqlVo.appendSql("AND A.BASE_ID in" + jointInSql(conditions.getBase_id()));
        if (StringUtils.isNotEmpty(conditions.getAttributes())) sqlVo.appendSql("AND A.ATTRIBUTES in" + jointInSql(conditions.getAttributes()));
        //if (StringUtils.isNotEmpty(conditions.getBin())) sqlVo.appendSql("AND A.BIN in" + jointInSql(conditions.getBin()));
        if (StringUtils.isNotEmpty(conditions.getLot_id())) sqlVo.appendSql("AND A.LOT_ID in" + jointInSql(conditions.getLot_id()));
        if (StringUtils.isNotEmpty(conditions.getStart_time())) sqlVo.appendSqlAndAddParam("AND CONCAT(INPUT_DATE, ' ', INPUT_TIME, ':00:00') >= ?", conditions.getStart_time()+":00:00");
        if (StringUtils.isNotEmpty(conditions.getEnd_time())) sqlVo.appendSqlAndAddParam("AND CONCAT(INPUT_DATE, ' ', INPUT_TIME, ':00:00') < ?", conditions.getEnd_time()+":00:00");

        List<HalmHourEfficiencyTrendReportGridOut> resultDatas = mySql_QueryRunner_QueryListBySql(sqlVo, HalmHourEfficiencyTrendReportGridOut.class);

        //所选档位的数据
        List<HalmHourEfficiencyTrendReportGridOut> gridOut_list = new ArrayList<>();
        resultDatas.stream()
                .filter(data -> StringUtils.isNotEmpty(data.getBin()))
                .collect(Collectors.groupingBy(data -> data.getDate())).forEach((date, list) -> {
                    int totalCount = list.stream().mapToInt(data -> Integer.parseInt(data.getCount())).sum();
                    int count = list.stream().filter(data -> StringUtils.isNotEmpty(conditions.getBin()) ? Arrays.asList(conditions.getBin().split(",")).contains(data.getBin()) : true).mapToInt(data -> Integer.parseInt(data.getCount())).sum();
                    double sumEta = list.stream().filter(data -> StringUtils.isNotEmpty(conditions.getBin()) ? Arrays.asList(conditions.getBin().split(",")).contains(data.getBin()) : true).mapToDouble(data -> Double.parseDouble(data.getEta_sum())).sum();
                    double average = getAverageRate(sumEta, count, 3);      //平均效率
                    double proportion = getRate(count, totalCount, 4);      //所占比例

                    HalmHourEfficiencyTrendReportGridOut gridOut = new HalmHourEfficiencyTrendReportGridOut();
                    gridOut.setDate(date);
                    gridOut.setHour(dateToHour(date));
                    gridOut.setAverage(average);
                    gridOut.setProportion(proportion);
                    gridOut_list.add(gridOut);
                });

        LKingSortUtil.sort(gridOut_list, new String[] { "date" }, new boolean[] { true });

        return gridOut_list;
    }

    private String dateToHour(String date_string) {
        String day = date_string.substring(8, 10).startsWith("0") ? date_string.substring(9, 10) : date_string.substring(8, 10);
        String start_hour = date_string.substring(11, 13).startsWith("0") ? date_string.substring(12, 13) : date_string.substring(11, 13);
        String end_hour = "23".equals(start_hour) ? "0" : String.valueOf(Integer.parseInt(start_hour) + 1);
        //return start_hour + ":00:00-" + end_hour + ":00:00";
        return day + "日 " + start_hour + "-" + end_hour + "时";
    }

}
